package com.hsnr.familyfinder;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

import android.os.Environment;
import android.util.Log;

public class MyLog {
    public static void i(String TAG, String message) {

        // Printing the message to LogCat console
        Log.i(TAG, message);

        // Write the log message to the file
        appendLog(message);
    }

    public static void d(String TAG, String message) {
        Log.d(TAG, message);
        appendLog(message);
    }

    public static void e(String TAG, String message) {
        Log.e(TAG, message);
        appendLog(message);
    }

    // rest of log methods...
    public static void appendLog(String text) {
        File root = Environment.getExternalStorageDirectory();
        File logFile = new File(root.getAbsolutePath() + File.separator + "FamilyFinder" + File.separator + "log.txt");
        if (!logFile.exists()) {
            try {
                logFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
            buf.append("[" + toDate(System.currentTimeMillis(), false) + "] " + text);
            buf.newLine();
            buf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String toDate(long timestamp, boolean timeOnly) {
        Date d = new Date(timestamp);
        StringBuilder sb = new StringBuilder();
        if (!timeOnly) {
            sb.append(d.getDate() + ".");
            sb.append(d.getMonth() + 1 + ".");
            sb.append((d.getYear() + 1900) + " ");
        }
        sb.append(((d.getHours() < 10) ? "0" : "") + d.getHours() + ":");
        sb.append(((d.getMinutes() < 10) ? "0" : "") + d.getMinutes()+":");
        sb.append(((d.getSeconds() < 10) ? "0" : "") + d.getSeconds());
        return sb.toString();
    }
}
